ARCH=riscv64
CC=$(ARCH)-linux-gnu-gcc
LD=$(ARCH)-linux-gnu-ld
OBJCOPY=$(ARCH)-linux-gnu-objcopy

CFLAGS=-Wall -Werror -O -fno-omit-frame-pointer -ggdb -gdwarf-2
CFLAGS+= -mcmodel=medany
CFLAGS+= -ffreestanding -fno-common -nostdlib -mno-relax
CFLAGS+= -I./include

LDFLAGS=-z max-page-size=4096

# 所有目标文件列表
OBJS = kernel/entry.o kernel/kalloc.o kernel/vm.o kernel/spinlock.o \
       kernel/uart.o kernel/lib.o kernel/test.o kernel/trampoline.o \
	   kernel/printf.o

# 默认目标：构建内核二进制文件
all: kernel.bin

# 链接生成ELF文件
kernel.elf: $(OBJS) kernel/kernel.ld
	$(LD) $(LDFLAGS) -T kernel/kernel.ld -o $@ $(OBJS)

# 转换为二进制文件
kernel.bin: kernel.elf
	$(OBJCOPY) -O binary $< $@

# 编译C文件
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# 编译汇编文件
%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

# 运行内核
run: kernel.bin
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.bin -nographic

# 调试内核
debug: kernel.bin
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.bin -nographic -s -S &
	riscv64-linux-gnu-gdb kernel.elf -ex "target remote localhost:1234" -ex "b _start"

# 清理编译产物
clean:
	rm -f *.bin *.elf $(OBJS)

# 伪目标
.PHONY: all run debug clean